package il.ac.tau.cvws.scrabblesidekick.server.servlet;

import il.ac.tau.cvws.scrabblesidekick.server.app.manager.GameManager;
import il.ac.tau.cvws.scrabblesidekick.server.util.debug.DebugUtil;
import il.ac.tau.cvws.scrabblesidekick.server.util.debug.DebugUtil.DebugTypes;
import il.ac.tau.cvws.scrabblesidekick.server.util.exception.ExceptionConstant;
import il.ac.tau.cvws.scrabblesidekick.server.util.exception.ScrabbleSidekickException;
import il.ac.tau.cvws.scrabblesidekick.server.util.file.ConversionUtil;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.request.CalibrateRequestData;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.response.CalibrateResponseData;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.response.ExceptionResponsePayload;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.response.ResponsePayload;
import il.ac.tau.cvws.scrabblesidekick.shared.datatype.StorageDataKey;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.javacv.cpp.opencv_core.IplImage;

@WebServlet("/CalibrationServlet")
@MultipartConfig
public class CalibrationServlet  extends ScrabbleSidekickServlet 
{
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		ResponsePayload responsePayload = null;
		
		try
		{
			CalibrateRequestData data = (CalibrateRequestData)getRequestPayload(request);
			
			DebugUtil.saveImage(IplImage.createFrom(ConversionUtil.convertStringToImage(data.getCalibrateImage().getImage())), 
								DebugTypes.CAL_SERVLET,
								"incoming_img", 
								true);

			StorageDataKey key = GameManager.instance().calibrateDevice(
					data.getCalibrateImage(),
					data.getScreenWidth(),
					data.getScreenHeight());
			
			if (key != null)
			{
				responsePayload = new CalibrateResponseData(key);
			}
			else
			{
				responsePayload = new ExceptionResponsePayload(ExceptionConstant.CALIBRATION_HAS_FAILED);
			}
		}
		catch (ScrabbleSidekickException e)
		{
			responsePayload = new ExceptionResponsePayload(e.getMSG());
		}

		sendResponsePayload(response, responsePayload);
	}
}
